<?php

namespace Home\Controller;

use Think\Controller;

class IndexController extends Controller
{
    public function login()
    {
        $appid = C("weixin.appId");
        $secret = C("weixin.appSecret");
        $code = I("get.code", "");
        $id = I("id");
        if (empty($code)) {
            $redirect_uri = "http://share.xunshengkj.com/index.php/index/login/";
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=$id";
            header("location:" . $url);
        } else {
            $id = I("get.state");
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
            $data = file_get_contents($url);
            $data = json_decode($data, true);
            $access_token = $data['access_token'];
            $openid = $data['openid'];
            if (!$openid) {
                $this->redirect("/index/login/id/$id");
            }
            $code = M('qrcode')->where(array('id' => $id))->find();
            $shop_id = $code['shop_id'];
            //获取微信用用户信息
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
            $data = file_get_contents($url);
            $data = json_decode($data, true);
            $user = M("wx_user")->where("openid='" . $openid . "'")->find();
            $saveInfo = array(
                'openid' => $openid,
                'nickname' => $data['nickname'],
                'sex' => $data['sex'],
                'city' => $data['city'],
                'province' => $data['province'],
                'country' => $data['country'],
                'headimgurl' => $data['headimgurl'],
                'shop_id' => $shop_id,
                'count' => 0,
                'hd_id' => $id,
                'scan_count' => 1
            );
            if (!$user) {
                $saveInfo['addtime'] = time();
                $user_id = M("wx_user")->add($saveInfo);
                session("user_id", $user_id);
            } else {
                M("wx_user")->where("openid='" . $openid . "'")->save($saveInfo);
                M("wx_user")->where("openid='" . $openid . "'")->setInc("scan_count", 1);//扫描次数加1
                session("user_id", $user['id']);
            }
            $openid=M('wx_user')->where(array('id'=>$user_id))->getField('openid');
            $count=M('wx_transfer')->where(array('codeid'=>$id,'openid'=>$openid,'state'=>1))->count();
            if($count>=1){
                $this->redirect("/Index/showinfo/id/$id");
            }
            else{
                $this->redirect("/Index/index/id/$id");
            }
        }
    }

    public function index()
    {
        $user_id = session("user_id");
        $id = I("id");
        $user = M('wx_user')->where(array('id' => $user_id))->find();
        M('wx_user')->where(array('openid' => $user['openid']))->setInc("scan_count", 1);//一进来就应该更新扫码次数

        $code = M('qrcode')->where(array('id' => $id))->find();
        $min_money = $code['money'] * 100;
        $max_money = $code['max_money'] * 100;
        $code_money = rand($min_money, $max_money);
        $data['money'] = $code_money;
        $data['state'] = 0;
        $re = M('wx_transfer')->add($data);
        session("hasid", $re);
        $shop_id = $code['shop_id'];
        if (empty($user_id) || empty($user)) {
            $this->redirect("/Index/login/id/$id");
        }
        $openid=M('wx_user')->where(array('id'=>$user_id))->getField('openid');
        $count=M('wx_transfer')->where(array('codeid'=>$id,'openid'=>$openid,'state'=>1))->count();
        if (empty($user['shop_id'])) {
            $data['shop_id'] = $shop_id;
            M("wx_user")->where("id='" . $user_id . "'")->save($data);
        }
        $shop = M('shop')->where(array('id' => $shop_id))->find();
        //检测商家到期时间，改变商家账户状态
        if ($shop['expiry_time'] < time()) {
            $data['state'] = 0;
            M('shop')->where(array('id' => $shop_id))->save($data);
            echo "商家帐号已到期";
            exit;
        }

        if ($code['status'] == 0) {
            echo "该商家生成的二维码有违规内容，已经被管理员禁止显示";
            exit;
        }
        session("shop_id", $shop_id);// 分享到朋友圈时显示商家的图片
        session("id", $id);// 分享到朋友圈时显示商家的图片
        $code['addtime'] = timeString($code['addtime']);
        $count = M('wx_transfer')->where(array('openid' => $user['openid'], 'codeid' => $id))->count();
        if ($count >= 1) {
            $this->redirect("/Index/showinfo/id/$id/from/scan");
        }
        $user_id = session("user_id");
        $shop_code = M('qrcode')->where(array("id" => $id))->find();
        $shop_code['image'] = "http://share.xunshengkj.com" . $shop_code['image'];
        $hdurl = "http://share.xunshengkj.com/Index/showinfo";
        $this->assign('hdurl', $hdurl);
        $this->assign('user_id', $user_id);
        $this->assign('shop_id', $shop_id);
        $this->assign("money", $code_money);//商家信息
        $this->assign('id', $id);
        $this->assign("shopinfo", $code);//二维码信息
        $this->assign("shopcode", $shop_code);//商家二维码信息
        $this->assign("shop", $shop);//商家信息*/
        $this->display();
    }

    public function give_wx_hongbao()
    {
        $user_id = session("user_id");
        $id = I("post.id");
        session("id", $id);
        $user = M('wx_user')->where(array('id' => $user_id))->find();
        $code = M('qrcode')->where(array('id' => $id))->find();//二维码信息
        $shop = M('shop')->where(array('id' => $code['shop_id']))->find();//商户信息
        $wx_user = M('wx_user')->where(array('id' => $user_id))->find();
        if (!$code || !$shop) {
            $arr['msg'] = "活动已经被商家删除,或商家不存在";
            $arr['code'] = 208;
            $this->ajaxReturn($arr);
        }
        $count = M('wx_transfer')->where(array('openid' => $wx_user['openid'], 'codeid' => $id))->count();
        if ($count >= 1) {
            $arr['msg'] = "你已经领取过了,禁止重复领取";
            $arr['code'] = 202;
            $this->ajaxReturn($arr);
        }
        $hasid = session("hasid");
        $code_money = M('wx_transfer')->where(array('id' => $hasid))->getField('money');
        $code_money = (int)$code_money;
        $wx_user = M('wx_user')->where(array('id' => $user_id))->find();
        if ($shop['money'] <= 0 || $shop['money'] < $code_money / 100) {
            $arr['msg'] = "商家账户余额不足以支付红包费用，请等待商家充值后再次尝试";
            $arr['code'] = 201;
            $this->ajaxReturn($arr);
        }
        if ($code['sheng_money'] < $code_money/100) {  //计算商家活动预算
            $arr['msg'] = "超出商家的活动预算";
            $arr['code'] = 207;
            $this->ajaxReturn($arr);
        } else {
                $openid = $wx_user['openid'];
                $amount = $code_money;
                $desc = "分享转账";
                $re_user_name = "haha";
                $rs = weixin_transfer_accounts($openid, $amount, $re_user_name, $desc);
                if ($rs['return_code'] == "SUCCESS" && $rs['result_code'] == "SUCCESS") {
                    $get_money = $code_money / 100;
                    $shop['money'] -= $get_money;//减去用户领取的红包金额
                    $data = array();
                    $code['sheng_money'] -= $get_money;//记录商家活动计划的剩余金额
                    $data['sheng_money'] = $code['sheng_money'];
                    $datas['money'] = $shop['money'];//记录商家余额
                    M('qrcode')->where(array('id' => $id))->save($data);
                    M('shop')->where(array('id' => $code['shop_id']))->save($datas);
                    $transfer_order = array(
                        'openid' => $rs['data']['openid'],
                        'state' => 1,
                        'money' => $rs['data']['amount'],
                        'desc' => $rs['data']['desc'],
                        'getip' => $rs['data']['spbill_create_ip'],
                        'order_number' => $rs['data']['partner_trade_no'],
                        'addtime' => time(),
                        'codeid' => $id,
                        'shop_id' => $code['shop_id'],
                        'plan_money' => $code['quota_money'],
                        'residue_money' => $code['sheng_money'],
                    );
                    $result = M('wx_transfer')->where(array('id' => $hasid))->save($transfer_order);
                    if ($result) {
                        $arr['msg'] = " 领取成功,请到微信钱包中查看";
                        $arr['code'] = 203;
                        $this->ajaxReturn($arr);
                    }
                } else {
                    if ($rs['err_code'] != NUll) {
                        $reason = $rs['err_code_des'];
                        $arr['msg'] = $reason;
                        $arr['code'] = 301;
                        $this->ajaxReturn($arr);
                    }
                }
            exit;
        }
    }

    public function showinfo()
    {
        $cid=I("post.cid");
        if($cid){
            $user_id=session("user_id");
            $user=M('wx_user')->where(array('id'=>$user_id))->find();
            M('wx_user')->where(array('openid' => $user['openid']))->setInc("count", 1);//一进来就应该更新分享次数
        }
        $id = session("id");
        if (empty($id)) {
            $id = I("get.id");
        }
        $from=I("get.from");
        if($from=="timeline") {
            $this->redirect("index/login/id/$id");
        }
            vendor("Jssdk.jssdk");
            $appId = C("jssdk.appId");
            $appSecret = C("jssdk.appSecret");
            $jssdk = new \JSSDK($appId, $appSecret);
            $signPackage = $jssdk->GetSignPackage();
            $user_id = session("user_id");
            $shopcode = M('qrcode')->where(array('id' => $id))->find();
            //更新活动浏览量
            $data['view'] = $shopcode['view'] + 1;
            M('qrcode')->where(array('id' => $id))->save($data);
            $shopcode['image'] = "http://share.xunshengkj.com" . $shopcode['image'];
            //检测字符串中是否含有html标签,有的话转义,没有的话就原样显示
            $shopcode['content'] = htmlspecialchars_decode($shopcode['content']);
            $successurl = "http://share.xunshengkj.com/Index/give_wx_hongbao";
            $this->assign('successurl', $successurl);
            $this->assign('signPackage', $signPackage);
            $this->assign('user_id', $user_id);
            $this->assign('id', $id);
            $this->assign('shopcode', $shopcode);
            $this->display();
        }
}